//
//  HMNetworkTool.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/17.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit
import AFNetworking

// 网络请求方式
enum HMNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class HMNetworkTool: NSObject {

    // 单例
    static let shared: HMNetworkTool = HMNetworkTool()
    
    // 直接使用AFN是有风险,如果哪天AFN没用了.项目中所有用到AFN的地方都要改
    // AFHttpSessionManager
    let afnManager: AFHTTPSessionManager
    
    fileprivate override init() {
        let urlString = "https://api.weibo.com/2/"
        let url = URL(string: urlString)
        afnManager = AFHTTPSessionManager(baseURL: url)
        // 设置afn支持的类型, 在原有的基础上添加一种
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
    }
    
    func request(method: HMNetworkMethod, URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        
        switch method {
        case .GET:
            print("get")
            afnManager.get(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
        case .POST:
            print("post")
            afnManager.post(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
        }
    }
    
    func post(URLString: String, parameters: Any?, constructingBodyWith: ((AFMultipartFormData) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        afnManager.post(URLString, parameters: parameters, constructingBodyWith: constructingBodyWith, progress: nil, success: success, failure: failure)
    }

    /*
    // 自己封装一个GET方法,如果AFN不能用了.只需要改这个方法.外面不需要做改动,
    func requestGET(URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        afnManager.get(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
    
    func requestPOST(URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        afnManager.post(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
 */
}
